package com.medeiros.upmoney.data;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import android.content.Context;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.medeiros.upmoney.model.Categoria;
import com.medeiros.upmoney.model.Limite;
import com.medeiros.upmoney.model.LimiteBuilder;

public class LimiteDataProvider {

	private static final LimiteDataProvider INSTANCE = new LimiteDataProvider();
	private Map<Categoria, Limite> limites;

	private String getAtualFileName(){
		Date date = new Date();
		return date.getYear()+"_"+date.getMonth();
	}
	public static LimiteDataProvider getInstance(){
		return INSTANCE;
	}

	private LimiteDataProvider(){
	}

	public void write(Context context, Limite limite){
		write(context, getAtualFileName(), limite);
	}

	public void write(Context context,String file, Limite limite){
		this.limites.put(limite.getCategoria(), limite);
		this.write(context, getAtualFileName());
	}

	public void write(Context context, String file){
		try {
			FileOutputStream fos = context.openFileOutput(file, Context.MODE_PRIVATE);
			fos.write(dataToJson(limites).getBytes());
			fos.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

	public Map<Categoria, Limite> read(Context context) throws IOException{
		return read(context, getAtualFileName());
	}

	public Map<Categoria, Limite> read(Context context, String file) throws IOException{
		if(this.limites == null){
			try {
				FileInputStream fis = context.openFileInput(file);
				FileReader fileReader = new FileReader(fis.getFD());
				this.limites =  dataFromJson(fileReader);
				fis.close();
			} catch (FileNotFoundException e) {
				if(this.limites == null){
					this.limites = getLimites();
				}
			}
		}
		return this.limites;
	}

	private String dataToJson(Map<Categoria, Limite> limites){
		return new Gson().toJson(limites);
	}

	private Map<Categoria, Limite> dataFromJson(FileReader data){
		Type mapType = getMapType();
		return new Gson().fromJson(data, mapType);
	}

	private Type getMapType() {
		Type mapType = new TypeToken<Map<Categoria, Limite>>() {}.getType();
		return mapType;
	}

	private Map<Categoria, Limite> getLimites() {
		int day = new Date().getDay() -1 ;
		Map<Categoria, Limite> limites = new HashMap<Categoria, Limite>();
		for (Categoria cat : Categoria.editaveis()) {
			limites.put(cat, LimiteBuilder.build(cat, 200, 0, -day));
		}
		return limites;

	}

}
